#/bin/bash
PATH=/bin:/sbin:/usr/bin/:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin
# ---------------------------------------------------------------------------------
# 字符云监控(xrkmonitor) 开源版 (c) 2020 by rockdeng
# 使用授权协议： apache license 2.0
#
# 开源演示版网址: http://open.xrkmonitor.com
# 云版本主页：http://xrkmonitor.com
#
# 云版本为开源版提供永久免费告警通道支持，告警通道支持短信、邮件、
# 微信等多种方式，欢迎使用
# ---------------------------------------------------------------------------------
#
# web 前端插件一键部署脚本
#
# 一键部署失败的处理方法
# 由于 apache 网站环境多样一键部署可能失败，如失败可手动如下处理
#
# 1、将插件部署包(一键部署功能会自动下载部署包到 agent xrkmonitor_plugin 目录下) 中的全部 js 文件拷贝到网站根目录
#    的 xrkmonitor目录下
# 2、拷贝插件部署包中的文件 _apache_monitor_website.conf 到 apache 配置文件目录下并重命名为 apache_monitor_website.conf 
# 3、修改文件 apache_monitor_website.conf 将 APACHE_DOCUMENT_ROOT 替换为实际的目录
# 4、在 apache 配置文件以及各虚拟主机配置中引入文件 apache_monitor_website.conf 
# 5、在 apache 网站以及各虚拟主机的入口文件(一般为 index.html) 中引入插件 js :
#       <script src=\'/xrkmonitor/dmt_xrkmonitor.js?v=111\'></script>
# 6、访问您的网站浏览器调试模式下看到 mt_slog_reportinfo cgi 调用或者监控控制台看到数据上报则说明部署成功了
#
#

# 网站入口文件
index_files=('index.html' 'index.htm' 'index.shtml' 'index.shtm')

# 入口文件插件脚本引入代码
enable_xrkjs="<script src=\'/xrkmonitor_plugin/dmt_xrkmonitor.js?v=111\'></script>"

# 正式使用时 agent 会设置 install_log_file, 手动调试可以自行设置
#install_log_file=/tmp/test_install
function AddInstallLog()
{
    if [ -f "$install_log_file" ]; then
        logt=`date '+%Y-%m-%d %H:%M:%S.%N'`
        echo "[ $logt ] shell - $1 " >> $install_log_file
    else
        echo $1
    fi
}

function GetApacheCfgPath()
{
    sAphServerCfgFile=`$APACHE_CMD -V|grep SERVER_CONFIG_FILE|awk -F "=" '{print $2}'`
    APH_SERVER_CONFIG_FILE=${sAphServerCfgFile//\"/}
    if [ ! -f "$APH_SERVER_CONFIG_FILE" ]; then
        sAphServerRoot=`$APACHE_CMD -V|grep HTTPD_ROOT|awk -F "=" '{print $2}'`
        APH_SERVER_CONFIG_PATH=${sAphServerRoot//\"/}
        if [ -d "$APH_SERVER_CONFIG_PATH" ]; then
            if [ -f "$APH_SERVER_CONFIG_PATH/$APH_SERVER_CONFIG_FILE" ]; then
                APH_SERVER_CONFIG_FILE=$APH_SERVER_CONFIG_PATH/$APH_SERVER_CONFIG_FILE;
                AddInstallLog "get apache config path:$APH_SERVER_CONFIG_PATH"
                AddInstallLog "get apache config file:$APH_SERVER_CONFIG_FILE"
                return
            fi
        fi
        echo "xrk_failed not find apache config file"
        exit 1
    fi
    AddInstallLog "get apache config file: $APH_SERVER_CONFIG_FILE"

    APH_SERVER_CONFIG_PATH=`dirname "$APH_SERVER_CONFIG_FILE"`
    if [ ! -d "$APH_SERVER_CONFIG_PATH" ]; then
        echo "xrk_failed not find apache config path!"
        exit 1
    fi
    AddInstallLog "get apache config path: $APH_SERVER_CONFIG_PATH"
}

function GetApacheCmd()
{
    apachectl -v > /dev/null 2>&1 
    if [ $? -eq 0 ]; then 
        APACHE_CMD=apachectl
    else
        apache2ctl -v > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            APACHE_CMD=apache2ctl
        else
            echo "xrk_failed not find apache cmd !"
            exit 1
        fi
    fi
    AddInstallLog "find apache exe cmd: $APACHE_CMD"
}

function GetApacheDocRoot()
{
    sDocRoot=`$APACHE_CMD -t -D DUMP_RUN_CFG 2>/dev/null |grep "Main DocumentRoot"|awk '{print $3}'`
    APACHE_DOCUMENT_ROOT=${sDocRoot//\"/}
    if [ -d "$APACHE_DOCUMENT_ROOT" ]; then
        AddInstallLog "find apache Main DocumentRoot: $APACHE_DOCUMENT_ROOT"
        return
    fi

    sAphConfList=`find "$APH_SERVER_CONFIG_PATH" -name "*.conf"`
    sDocRootList=`grep -v "[[:space:]]*#" "$sAphConfList" |grep DocumentRoot |awk -F ":" '{if(NR==1) print $2; else print ":"$2}'`
    IFSBAK=$IFS
    IFS=':'
    for sDoc in $sDocRootList
    do
        sDocRoot=`echo "$sDoc" |awk '{print $2 }'`
        APACHE_DOCUMENT_ROOT=${sDocRoot//\"/}
        if [  -d "$APACHE_DOCUMENT_ROOT" ]; then
            break;
        fi
    done
    IFS=$IFSBAK

    if [ -d "$APACHE_DOCUMENT_ROOT" ]; then
        AddInstallLog "find apache Main DocumentRoot: $APACHE_DOCUMENT_ROOT"
    else
        echo "xrk_failed not find apache main documentroot!"
        exit 1
    fi
}

function AddPLuginJsToIndexFile()
{
    indexflist=`ls -1 "$APACHE_DOCUMENT_ROOT"`
    
    for inx_file in ${index_files[@]}; do
    	indexf=`echo "$indexflist"|grep -e "^${inx_file}$"`
        if [ $? -ne 0 -o ! -f "$APACHE_DOCUMENT_ROOT/$indexf" ]; then
            indexf=''
            continue
        else
            break;
        fi
    done
	
    if [ "$indexf" == '' ]; then
        AddInstallLog "warning - not find apache site index file, document root:$APACHE_DOCUMENT_ROOT"
        return;
    fi

    cat "$APACHE_DOCUMENT_ROOT/$indexf" |grep "dmt_xrkmonitor.js" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        AddInstallLog "already insert plugin js file to index file:$APACHE_DOCUMENT_ROOT/$indexf"
    else
        hline=`cat $APACHE_DOCUMENT_ROOT/$indexf |grep -i "<head>"`
        shline=`echo $hline`
        if [ "$shline" != "<head>" -a "$shline" != "<HEAD>" ]; then
            # <head> 标签没有独占一行，不处理此种情况, 强行插入可能弄乱 html 标签
            AddInstallLog "warn file: $APACHE_DOCUMENT_ROOT/$indexf <head> mark not hold one line, skip it"
            xrk_failed=`expr $xrk_failed + 1`
        else
            if [ "$shline" == "<head>" ]; then
                sed -i "/<head>/a$enable_xrkjs" $APACHE_DOCUMENT_ROOT/$indexf 
            else
                sed -i "/<HEAD>/a$enable_xrkjs" $APACHE_DOCUMENT_ROOT/$indexf 
            fi
            cat $APACHE_DOCUMENT_ROOT/$indexf |grep "dmt_xrkmonitor.js"  > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                AddInstallLog " [ change ] - insert plugin js file to index file:$APACHE_DOCUMENT_ROOT/$indexf ok"
                xrk_success=`expr $xrk_success + 1`
            else
                xrk_failed=`expr $xrk_failed + 1`
                AddInstallLog "insert plugin js file to index file:$APACHE_DOCUMENT_ROOT/$indexf failed"
            fi
        fi
    fi
}

if [ ! -f ./_apache_monitor_website.conf ]; then
    AddInstallLog "not find config file:_apache_monitor_website.conf"
    exit $LINENO
fi

GetApacheCmd
GetApacheCfgPath
GetApacheDocRoot

# 创建插件 js 文件目录
if [ ! -d "$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin" ]; then
    mkdir -p "$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin" > /dev/null 2>&1
    if [ ! -d "$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin" ]; then
        echo "xrk_failed create dir: $APACHE_DOCUMENT_ROOT/xrkmonitor_plugin"
        exit 1
    fi
    AddInstallLog "[ change ] - create js file dir: $APACHE_DOCUMENT_ROOT/xrkmonitor_plugin ok"
else
    AddInstallLog "js file dir: $APACHE_DOCUMENT_ROOT/xrkmonitor_plugin has exist"
fi

# 拷贝插件 js 文件
cp *.js "$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin" > /dev/null 2>&1
if [ ! -f "$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin/dmt_xrkmonitor.js" ]; then
    echo "copy js file to dir:$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin failed"
    exit 1
fi
AddInstallLog "[ change ] - copy js file to dir:$APACHE_DOCUMENT_ROOT/xrkmonitor_plugin ok"

# 生成 apache 插件部署配置文件到 apache 配置目录
pt_docroot=${APACHE_DOCUMENT_ROOT/\\\//\//}
sed "s#APACHE_DOCUMENT_ROOT#$pt_docroot#g" _apache_monitor_website.conf > "$APH_SERVER_CONFIG_PATH/apache_monitor_website.conf"
if [ -f "$APH_SERVER_CONFIG_PATH/apache_monitor_website.conf" ]; then
    AddInstallLog "[ change ] - create apache config file:$APH_SERVER_CONFIG_PATH/apache_monitor_website.conf"
else
    AddInstallLog "create apache config file:$APH_SERVER_CONFIG_PATH/apache_monitor_website.conf failed !"
    exit 1
fi

xrk_success=0
xrk_failed=0

#修改 apache 默认配置文件，加入插件的 apache 配置文件 
incFile="Include $APH_SERVER_CONFIG_PATH/apache_monitor_website.conf"
cat "$APH_SERVER_CONFIG_FILE" |grep "$incFile" > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "$incFile" >> "$APH_SERVER_CONFIG_FILE"
    cat "$APH_SERVER_CONFIG_FILE" |grep "$incFile" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        AddInstallLog "[ change ] - add $incFile to file: $APH_SERVER_CONFIG_FILE ok"
        xrk_success=`expr $xrk_success + 1`
    else
        AddInstallLog "add $incFile in file: $APH_SERVER_CONFIG_FILE failed !"
        xrk_failed=`expr $xrk_failed + 1`
    fi
else
    AddInstallLog "already add |$incFile| in file: $APH_SERVER_CONFIG_FILE"
fi

#默认网站入口文件
AddInstallLog "try add plugin js to default site index file, site doc root:$APACHE_DOCUMENT_ROOT"
AddPLuginJsToIndexFile

# 虚拟主机处理, 引入插件配置文件, 入口文件引入插件 js 
sAphConfList=`$APACHE_CMD -t -D DUMP_INCLUDES|awk '{if(NR!=1)print $2}'|sort -u`
if [ "$sAphConfList" == '' ]; then
    sAphConfList=`find "$APH_SERVER_CONFIG_PATH" -name "*.conf"`
fi
sVHostFileList=`grep -v "[[:space:]]*#" $sAphConfList|grep "<VirtualHost" |awk -F ":" '{ print $1}'|sort -u`
for sVF in $sVHostFileList
do
    cat "$sVF" |grep "$incFile" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        sed -i "/<VirtualHost/a$incFile" "$sVF"
        cat "$sVF" |grep "$incFile" > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            AddInstallLog " [ change ] - add $incFile in file: $sVF ok"
            xrk_success=`expr $xrk_success + 1`
        else
            AddInstallLog "add $incFile in file: $sVF failed"
            xrk_failed=`expr $xrk_failed + 1`
            continue
        fi
    else
        AddInstallLog "already add |$incFile| in file: $sVF"
    fi

# 各虚拟主机入口文件, 引入插件js
    sDocRootList=`grep -v "[[:space:]]*#" "$sVF"| grep DocumentRoot|awk '{print $2}'`
    for sDoc in $sDocRootList
    do
        sDocRoot=`echo "$sDoc"`
        APACHE_DOCUMENT_ROOT=${sDocRoot//\"/}
        if [ -d "$APACHE_DOCUMENT_ROOT" ]; then
            AddInstallLog "try add plugin js to vhost site index file, document root:$APACHE_DOCUMENT_ROOT"
            AddPLuginJsToIndexFile
        else
            AddInstallLog "warning visual host document root:$APACHE_DOCUMENT_ROOT not exist !"
        fi
    done
done

if [ $xrk_failed -eq 0 ]; then 
    echo "xrk_success $xrk_success $xrk_failed";
elif [ $xrk_success -gt 0 ]; then
    echo "xrk_psuccess $xrk_success $xrk_failed";
else
    echo "xrk_failed $xrk_success $xrk_failed";
fi

echo "#!/bin/bash" > install_env.sh
echo "APACHE_CMD=$APACHE_CMD" >> install_env.sh
echo "APACHE_DOCUMENT_ROOT=$APACHE_DOCUMENT_ROOT" >> install_env.sh
echo "APACHE_CFG_FILE=\"$APH_SERVER_CONFIG_PATH/apache_monitor_website.conf\"" >> install_env.sh
echo "APH_SERVER_CONFIG_FILE=\"$APH_SERVER_CONFIG_FILE\"" >> install_env.sh
echo "APH_SERVER_CONFIG_PATH=\"$APH_SERVER_CONFIG_PATH\"" >> install_env.sh
chmod +x install_env.sh > /dev/null 2>&1

if [ $xrk_success -gt 0 ]; then
    $APACHE_CMD restart > /dev/null 2>&1
fi

